<?php

namespace app\api\controller\app;

use app\admin\controller\order\Shoptableorder;
use app\admin\model\Banner;
use app\admin\model\City;
use app\admin\model\common\Sim;
use app\admin\model\money\Platform;
use app\admin\model\Org;
use app\admin\model\OrgIndexNotice;
use app\admin\model\OrgNotice;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\shop\Commission;
use app\admin\model\shop\Withdraw;
use app\admin\model\Shopcharge;
use app\admin\model\Shopdaytrade;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;
use app\api\service\DeviceService;
use app\api\service\MeituanService;
use app\api\service\MtService;
use app\api\service\MtUtil;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Validate;

/**
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function updateMtToken()
    {

        $shopModel = new Shop();
        $time = strtotime("+1 day");
        $list = $shopModel->where('mt_update_time', "<", $time)->where('mt_token', '<>', '')->where('mt_refresh_token', "<>", '')->select();

        $mtService = new MtService();
        foreach ($list as $key => $val) {

            if ($val['is_sync'] == 1) {
                $req = array();
                $req['shop_id'] = $val['id'];
                $mtService->refreshToken($req);
            }

        }
        $this->success('成功', $list);

    }


    public function refreshMeituanToken()
    {

        $shopModel = new Shop();
        $time = strtotime("+1 day");
        $list = $shopModel->where('mt2_update_time', "<", $time)->where('mt2_token', '<>', '')->where('mt2_refresh_token', "<>", '')->select();

        $meituanService = new MeituanService();
        foreach ($list as $key => $val) {
            $req = array();
            $req['shop_id'] = $val['id'];
            $req['refreshToken'] = $val['mt2_refresh_token'];
            $meituanService->refreshToken($req);
        }
        $this->success('成功', $list);

    }


    public function updateBookTask()
    {

        $endTime = strtotime("-3 minute", time());
        $shopOrderBookModel = new Shoproombook();
        $shopCleanModel = new Roomclean();
        $list = $shopOrderBookModel->where('end_time', "<=", $endTime)->where('status', 'in', ['doing', 'undo'])->order('end_time', 'desc')->limit(10)->select();
        $shopOrderModel = new Shoporder();
        $shopRoomModel = new Shoproom();
        foreach ($list as $key => $val) {
            $shopOrderModel->where('id', $val['order_id'])->update(['status' => 'done']);

            $endTime = strtotime("+30 minute", $val['end_time']);
            if (time() >= $endTime) {
                $shopCleanModel->where('order_id', $val['order_id'])->update(['status' => 'done']);
            }
            $shopOrderBookModel->where('id', $val['id'])->update(['status' => 'done']);
            $shopRoomModel->where('id', $val['room_id'])->update(['status' => 'free', 'is_clean' => -1]);

        }
        $this->success('', $list);
    }


    public function updateBookTask2()
    {

        $endTime = strtotime("-3 minute", time());
        $shopOrderBookModel = new Shoproombook();
        $shopCleanModel = new Roomclean();
        $list = $shopOrderBookModel->where('end_time', "<=", $endTime)->where('status', 'in', ['doing', 'undo'])->order('end_time', 'desc')->limit(10)->select();

        $this->success('', $list);
    }


    public function doOrderTask(DeviceService $deviceService)
    {

        //error_log("====doOrderTask======".date("Y-m-d H:i:s"));
        $shopOrderModel = new Shoporder();
        $shopOrderBookModel = new Shoproombook();
        $shopRoomModel = new Shoproom();
        $deviceModel = new Shopdevice();
        $list = $shopOrderModel->where('org_id', 76)->where('status', 'doing')->order('book_end', 'asc')->limit(50)->select();
        foreach ($list as $key => $val) {

            if ($val['book_end'] <= time()) {
                //关闭订单
                $shopOrderModel->where('id', $val['id'])->update(['status' => 'done']);
                $shopOrderBookModel->where('order_id', $val['id'])->update(['status' => 'done']);

                $shopRoomModel->where('id', $val['room_id'])->update(['status' => 'free', 'is_clean' => -1]);


                $device = $deviceModel->where('room_id', $val['room_id'])->where('device_type', 'qp')->find();

                $doorReq = array();
                $doorReq['open'] = 0;
                $doorReq['open2'] = 0;
                $doorReq['open3'] = 0;
                $doorReq['open4'] = 0;
                $doorReq['device_sn'] = $device['device_sn'];

                $timeReq = array();
                $timeReq['device_sn'] = $device['device_sn'];
                $timeReq['sec'] = 0;
                $timeReq['time'] = time();
                $deviceService->dxIotDoor($doorReq);
                $deviceService->dxIotTime($timeReq);

            }

        }
    }

    //0抽佣（每个月10号、20号、28号凌晨4点 19分检测）
    public function doCommission()
    {
        $shopCommissionSetModel = new Commission();
        $shopCommissionInfos = $shopCommissionSetModel->where('start_date', '<=', time())->select();
        if (!empty($shopCommissionInfos)) {
            foreach ($shopCommissionInfos as $shopCommissionInfo) {
                //查询当月是否已经抽佣，如果没有则需要主动发起抽佣
                $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00', time()));
                $shopWitdrawModel = new Withdraw();
                $list = $shopWitdrawModel->where('shop_id', $shopCommissionInfo['shop_id'])->where('type', 1)->where('createtime', '>=', $firstDayOfMonth)->find();
                if (empty($list)) {
                    $shopModel = new Shop();
                    $shopInfo = $shopModel->where('id', $shopCommissionInfo['shop_id'])->find();
                    //计算该店铺需要抽佣的金额
                    $minAmount = $this->getShopMinMoney($shopCommissionSetModel, $shopModel, $shopCommissionInfo);
                    if ($minAmount > 0) {
                        //将需要扣除有的佣金金额写入用户提现表
                        $nowTime = time();
                        $userWithDrawModel = new Userwithdraw();
                        $newDb['user_id'] = $shopInfo['user_id'];
                        $newDb['type'] = 'shop';
                        $newDb['user_name'] = '系统自动扣除';
                        $newDb['bank_num'] = '扣除店铺当月平台服务费';
                        $newDb['amount'] = $minAmount;
                        $newDb['back_amount'] = $minAmount;
                        $newDb['create_time'] = $nowTime;
                        $newDb['status'] = 'success';
                        $userWithDrawModel->insert($newDb);

                        //写入系统店铺抽佣记录
                        $nowMonth = date('Y年m月', time());
                        $lastDb['user_id'] = $shopInfo['user_id'];
                        $lastDb['shop_id'] = $shopInfo['id'];
                        $lastDb['type'] = 1;
                        $lastDb['amount'] = $minAmount;
                        $lastDb['remark'] = $nowMonth . ' 店铺抽佣';
                        $lastDb['createtime'] = $nowTime;

                        $shopWitdrawModel->insert($lastDb);
                    }
                }
            }
        }
        $this->success('执行完成');
    }

    //全平台抽佣（每天凌晨5点30，执行）
    public function doAllCommission()
    {
        $shopModel = new Shop();
        $shops = $shopModel->where('profit_type', 2)->where('status', 'in', [1, 2])->select();
        if (!empty($shops)) {

            //查询头一天的起止时间戳
            $st = strtotime(date('Y-m-d 00:00:00', time() - 86400));
            $et = strtotime(date('Y-m-d 00:00:00', time()));

            //统计的日期
            $date = date('m月d日', time() - 86400);
            foreach ($shops as $shop) {
                $shopMtDyModel = new Shopmtdyprofit();
                $mtDouProfit = $shopMtDyModel->where('shop_id', $shop['id'])->where('create_time', '>=', $st)->where('create_time', '<', $et)->sum('profit');
                if ($mtDouProfit > 0) {
                    //写入抽佣提现
                    $newDb['user_id'] = $shop['user_id'];
                    $newDb['type'] = 'shop';
                    $newDb['user_name'] = '全平台美团抖音的扣款';
                    $newDb['bank_num'] = $date . '美团抖音的扣款';
                    $newDb['amount'] = $mtDouProfit;
                    $newDb['back_amount'] = $mtDouProfit;
                    $newDb['create_time'] = time() - 86400;
                    $newDb['status'] = 'success';

                    $userWithDrawModel = new Userwithdraw();
                    $userWithDrawModel->insert($newDb);

                    //写入系统店铺抽佣记录
                    $shopWitdrawModel = new Withdraw();
                    $lastDb['user_id'] = $shop['user_id'];
                    $lastDb['shop_id'] = $shop['id'];
                    $lastDb['type'] = 0;
                    $lastDb['amount'] = $mtDouProfit;
                    $lastDb['remark'] = $date . '美团抖音的扣款';
                    $lastDb['createtime'] = time() - 86400;

                    $shopWitdrawModel->insert($lastDb);

                }
            }

        }

        $this->success('执行完成');
    }

    //定时执行扣除指定店铺的指定费用（每月8号、18号以及28号凌晨4:30开始执行）
    public function doSim()
    {
        $shopSimModel = new Sim();
        $shops = $shopSimModel->where('deletetime', null)->select();
        if (!empty($shops)) {
            foreach ($shops as $shop) {
                //执行月份
                $st = strtotime($shop['start_date'] . '-01 00:00:00');
                if ($st > time()) {
                    //获取上一次的金额扣除
                    if (!empty($shop['last_amount'])) {
                        //判断是否存在本月的扣费记录
                        $this->checkShopWitdraw($shop['last_amount'], $shop);
                    }
                } else {
                    $this->checkShopWitdraw($shop['amount'], $shop);
                }
            }
        }

        $this->success('执行完成');

    }

    //每天定时统计支付收益到【q_platform_profit】表，凌晨2:05分开始执行

    /**
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function doQpProfit()
    {
        //查询头一天的起止时间戳
        $st = strtotime(date('Y-m-d 00:00:00', time() - 86400));
        $et = strtotime(date('Y-m-d 00:00:00', time())) - 1;

        $shopOrderModel = new Shoporder();
        $shopModel = new Shop();
        $platformModel = new Platform();
        $orderList = $shopOrderModel->where('status', 'in', ['payed', 'doing', 'done'])->whereBetween('create_time', [$st, $et])->where('pay_amount', '>', 0)->select();
        $insertVal = array();
        foreach ($orderList as $v) {
            $shop_id = $v['shop_id'];
            $time = $v['create_time'];
            $payAmount = $v['pay_amount'];
            $orderId = $v['id'];

            $shopInfo = $shopModel->where('id', $shop_id)->find();
            if (empty($shopInfo)) {
                $uid = -1;
                $pay_rate = 0.6;
                $ratio = 5;
                $agent_id = -1;
                $agent_ratio = 0;
            } else {
                $uid = $shopInfo['user_id'];
                $pay_rate = $shopInfo['pay_rate'];
                $ratio = $shopInfo['ratio'];
                $agent_id = $shopInfo['agent_id'];
                $agent_ratio = $shopInfo['agent_ratio'];
            }

            $pay_rate_amount = formatMoney($payAmount * $pay_rate / 100);//支付通道费
            $shop_profit = formatMoney($payAmount * (100 - $ratio - $pay_rate) / 100);//商家收益
            $agent_amount = formatMoney($payAmount * $agent_ratio / 100);//代理商费
            $platform_amount = formatMoney($payAmount - $pay_rate_amount - $shop_profit - $agent_amount);//平台实际抽佣

            $db = array();
            $db['shop_id'] = $shop_id;
            $db['user_id'] = $uid;
            $db['order_id'] = $orderId;
            $db['order_pay_amount'] = $payAmount;
            $db['shop_amount'] = $shop_profit;
            $db['pay_rate'] = $pay_rate_amount;
            $db['agent_id'] = $agent_id;
            $db['agent_rate'] = $agent_amount;
            $db['rate'] = $platform_amount;
            $db['type'] = 'order';
            $db['from'] = 'qp';
            $db['createtime'] = $time;

            $insertVal[] = $db;
        }

        $platformModel->insertAll($insertVal);

        $this->success('统计棋牌支付，执行完成');
    }

    //每天定时统计-台球【q_shop_table_order】表支付收益到【q_platform_profit】表，凌晨2:08分开始执行

    /**
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function doTqProfit()
    {
        //查询头一天的起止时间戳
        $st = strtotime(date('Y-m-d 00:00:00', time() - 86400));
        $et = strtotime(date('Y-m-d 00:00:00', time())) - 1;

        $shopOrderModel = new \app\admin\model\Shoptableorder();
        $shopModel = new Shop();
        $platformModel = new Platform();
        $orderList = $shopOrderModel->where('status', 'in', ['doing', 'done'])->whereBetween('book_end', [$st, $et])->where('pay_amount', '>', 0)->select();
        $insertVal = array();
        foreach ($orderList as $v) {
            $shop_id = $v['shop_id'];
            $time = $v['book_end'];
            $payAmount = $v['pay_amount'];
            $orderId = $v['id'];

            $shopInfo = $shopModel->where('id', $shop_id)->find();
            if (empty($shopInfo)) {
                $uid = -1;
                $pay_rate = 0.6;
                $ratio = 5;
                $agent_id = -1;
                $agent_ratio = 0;
            } else {
                $uid = $shopInfo['user_id'];
                $pay_rate = $shopInfo['pay_rate'];
                $ratio = $shopInfo['ratio'];
                $agent_id = $shopInfo['agent_id'];
                $agent_ratio = $shopInfo['agent_ratio'];
            }

            $pay_rate_amount = formatMoney($payAmount * $pay_rate / 100);//支付通道费
            $shop_profit = formatMoney($payAmount * (100 - $ratio - $pay_rate) / 100);//商家收益
            $agent_amount = formatMoney($payAmount * $agent_ratio / 100);//代理商费
            $platform_amount = formatMoney($payAmount - $pay_rate_amount - $shop_profit - $agent_amount);//平台实际抽佣

            $db = array();
            $db['shop_id'] = $shop_id;
            $db['user_id'] = $uid;
            $db['order_id'] = $orderId;
            $db['order_pay_amount'] = $payAmount;
            $db['shop_amount'] = $shop_profit;
            $db['pay_rate'] = $pay_rate_amount;
            $db['agent_id'] = $agent_id;
            $db['agent_rate'] = $agent_amount;
            $db['rate'] = $platform_amount;
            $db['type'] = 'order';
            $db['from'] = 'tq';
            $db['createtime'] = $time;

            $insertVal[] = $db;
        }

        $platformModel->insertAll($insertVal);

        $this->success('统计台球订单支付，执行完成');
    }

    //每天定时统计-充值【q_shop_charge】表支付收益到【q_platform_profit】表，凌晨2:10分开始执行

    /**
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function doChargeProfit()
    {
        //查询头一天的起止时间戳
        $st = strtotime(date('Y-m-d 00:00:00', time() - 86400));
        $et = strtotime(date('Y-m-d 00:00:00', time())) - 1;

        $shopOrderModel = new Shopcharge();
        $shopModel = new Shop();
        $platformModel = new Platform();
        $orderList = $shopOrderModel->where('status', 'payed')->whereBetween('create_time', [$st, $et])->select();
        $insertVal = array();
        foreach ($orderList as $v) {
            $shop_id = $v['shop_id'];
            $time = $v['create_time'];
            $payAmount = $v['amount'];
            $orderId = $v['id'];

            $shopInfo = $shopModel->where('id', $shop_id)->find();
            if (empty($shopInfo)) {
                $uid = -1;
                $pay_rate = 0.6;
                $ratio = 5;
                $agent_id = -1;
                $agent_ratio = 0;
            } else {
                $uid = $shopInfo['user_id'];
                $pay_rate = $shopInfo['pay_rate'];
                $ratio = $shopInfo['ratio'];
                $agent_id = $shopInfo['agent_id'];
                $agent_ratio = $shopInfo['agent_ratio'];
            }

            $pay_rate_amount = formatMoney($payAmount * $pay_rate / 100);//支付通道费
            $shop_profit = formatMoney($payAmount * (100 - $ratio - $pay_rate) / 100);//商家收益
            $agent_amount = formatMoney($payAmount * $agent_ratio / 100);//代理商费
            $platform_amount = formatMoney($payAmount - $pay_rate_amount - $shop_profit - $agent_amount);//平台实际抽佣

            $db = array();
            $db['shop_id'] = $shop_id;
            $db['user_id'] = $uid;
            $db['order_id'] = $orderId;
            $db['order_pay_amount'] = $payAmount;
            $db['shop_amount'] = $shop_profit;
            $db['pay_rate'] = $pay_rate_amount;
            $db['agent_id'] = $agent_id;
            $db['agent_rate'] = $agent_amount;
            $db['rate'] = $platform_amount;
            $db['type'] = 'charge';
            $db['from'] = 'qp';
            $db['createtime'] = $time;

            $insertVal[] = $db;
        }

        $platformModel->insertAll($insertVal);

        $this->success('统计充值支付，执行完成');
    }

    //每天定时统计-团购券【q_platform_profit】表支付收益到【q_platform_profit】表，凌晨2:12分开始执行

    /**
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     */
    public function doTuanProfit()
    {
        //查询头一天的起止时间戳
        $st = strtotime(date('Y-m-d 00:00:00', time() - 86400));
        $et = strtotime(date('Y-m-d 00:00:00', time())) - 1;

        $shopOrderModel = new Tuanorder();
        $shopModel = new Shop();
        $platformModel = new Platform();
        $orderList = $shopOrderModel->where('status', 'payed')->whereBetween('create_time', [$st, $et])->select();
        $insertVal = array();
        foreach ($orderList as $v) {
            $shop_id = $v['shop_id'];
            $time = $v['create_time'];
            $payAmount = $v['amount'];
            $orderId = $v['id'];

            $shopInfo = $shopModel->where('id', $shop_id)->find();
            if (empty($shopInfo)) {
                $uid = -1;
                $pay_rate = 0.6;
                $ratio = 5;
                $agent_id = -1;
                $agent_ratio = 0;
            } else {
                $uid = $shopInfo['user_id'];
                $pay_rate = $shopInfo['pay_rate'];
                $ratio = $shopInfo['ratio'];
                $agent_id = $shopInfo['agent_id'];
                $agent_ratio = $shopInfo['agent_ratio'];
            }

            $pay_rate_amount = formatMoney($payAmount * $pay_rate / 100);//支付通道费
            $shop_profit = formatMoney($payAmount * (100 - $ratio - $pay_rate) / 100);//商家收益
            $agent_amount = formatMoney($payAmount * $agent_ratio / 100);//代理商费
            $platform_amount = formatMoney($payAmount - $pay_rate_amount - $shop_profit - $agent_amount);//平台实际抽佣

            $db = array();
            $db['shop_id'] = $shop_id;
            $db['user_id'] = $uid;
            $db['order_id'] = $orderId;
            $db['order_pay_amount'] = $payAmount;
            $db['shop_amount'] = $shop_profit;
            $db['pay_rate'] = $pay_rate_amount;
            $db['agent_id'] = $agent_id;
            $db['agent_rate'] = $agent_amount;
            $db['rate'] = $platform_amount;
            $db['type'] = 'tuan';
            $db['from'] = 'qp';
            $db['createtime'] = $time;

            $insertVal[] = $db;
        }

        $platformModel->insertAll($insertVal);

        $this->success('统计团购券支付，执行完成');
    }

    //执行sim卡扣费方法
    protected function checkShopWitdraw($amount, $shop)
    {
        $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00', time()));
        $shopWitdrawModel = new Withdraw();
        $userWithDrawModel = new Userwithdraw();
        $list = $shopWitdrawModel->where('shop_id', $shop['shop_id'])->where('type', 2)->where('createtime', '>=', $firstDayOfMonth)->find();
        if (empty($list)) {
            $newDb['user_id'] = $shop['user_id'];
            $newDb['type'] = 'shop';
            $newDb['user_name'] = '系统自动扣除';
            $newDb['bank_num'] = '扣除店铺当月sim卡费';
            $newDb['amount'] = $amount;
            $newDb['back_amount'] = $amount;
            $newDb['create_time'] = time();
            $newDb['status'] = 'success';
            $userWithDrawModel->insert($newDb);

            //写入系统店铺扣费记录
            $nowMonth = date('Y年m月', time());
            $lastDb['user_id'] = $shop['user_id'];
            $lastDb['shop_id'] = $shop['shop_id'];
            $lastDb['type'] = 2;
            $lastDb['amount'] = $amount;
            $lastDb['remark'] = $nowMonth . ' 店铺sim卡费';
            $lastDb['createtime'] = time();

            $shopWitdrawModel->insert($lastDb);

        }
    }

    protected function getShopMinMoney($shopCommissionSetModel, $shopModel, $shopCommissionInfo)
    {
        $shopRoomModel = new Shoproom();
        //查询店铺包厢数量
        $shopRoom = $shopRoomModel->where('shop_id', $shopCommissionInfo['shop_id'])->count();
        //查询台桌数量
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopTable = $shopTableModel->where('shop_id', $shopCommissionInfo['shop_id'])->count();
        $total = $shopRoom + $shopTable;

        //查询抽佣的相关参数
        if ($shopCommissionInfo['is_open'] == '-1') {
            //变更抽佣设置表的开启状态
            $shopCommissionSetModel->where('shop_id', $shopCommissionInfo['shop_id'])->update(['is_open' => 1]);

            //变更店铺对应的抽佣方式
            $shopModel->where('id', $shopCommissionInfo['shop_id'])->update(['ratio' => 0.00, 'profit_type' => 1, 'is_all' => -1]);
        }

        if ($total <= 7) {
            $totalMoney = $shopCommissionInfo['min_amount'];
        } else {
            $totalMoney = $shopCommissionInfo['min_amount'] + ($total - 7) * $shopCommissionInfo['single_amount'];
        }

        return $totalMoney;
    }


}
